﻿create procedure [store].[kvkvDestroy]
(
	@Key varchar(255),
	@Version int
)
as 
begin 

	declare @deleted table
	(
		KeyId bigint primary key not null,
		DeletedVersion int not null
	)

	delete store.[kvPersisted] 
	output deleted.KeyId, deleted.[Version] into @deleted
	where [Key] = @Key

	if @@rowcount = 0 return;
	
	declare @DeletedVersion binary(8)
	select @DeletedVersion = DeletedVersion from @deleted
	 
	if @Version != @DeletedVersion 
			begin
				declare @message nvarchar(350)
				set @message = 'Concurrency violation for key [' + @Key + ']. Reselect the value and try again.';
				throw 60001, @message, 1;
			end

	declare @KeyId bigint
	select @KeyId = KeyId from @deleted
	delete from store.[kvPersistedValues] where [KeyId] = @KeyId
end
